﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using BaseData;
using BaseLib.Helper;
using BaseUtility;
using Newtonsoft.Json;
namespace WebUI.Ashx.App
{
    /// <summary>
    /// UploadFiles 的摘要说明
    /// </summary>
    public class UploadFiles : Base, IHttpHandler
    {
        private HttpContext _context;
        private static readonly AccClass _accId = new AccExts(new GetAccType().Parse(Request.QueryString["url"])).Instances;
        public void ProcessRequest(HttpContext context)
        {
            if (_accId.Id == 0 || string.IsNullOrWhiteSpace(_accId.Name) || _accId.Type == 0) return;
            var hash = new Hashtable();
            try
            {
                var aspxUrl = context.Request.Path.Substring(0, context.Request.Path.LastIndexOf("/", System.StringComparison.Ordinal) + 1);
                //文件保存目录路径
                const string savePath = "/attached/";
                //文件保存目录URL
                var saveUrl = "/attached/"; // aspxUrl + "/attached/"
                //定义允许上传的文件扩展名
                var extTable = new Hashtable
		        {
		            {"image", "gif,jpg,jpeg,png,bmp"},
		            {"flash", "swf,flv,f4v,fla"},
		            {"media", "mp3,mp4,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb"},
		            {"file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2"}
		        };
                //最大文件大小
                const int maxSize = 1024000000;
                this._context = context;
                var imgFile = context.Request.Files["imgFile"];
                if (imgFile == null) ShowError("请选择文件。");
                var dirPath = context.Server.MapPath(savePath);
                if (!Directory.Exists(dirPath)) ShowError("上传目录" + savePath + "不存在。");
                var dirName = context.Request.QueryString["dir"];
                if (String.IsNullOrEmpty(dirName)) dirName = "images";
                if (!extTable.ContainsKey(dirName)) ShowError("目录名不正确。");
                var fileName = imgFile.FileName;
                var fileExt = Path.GetExtension(fileName).ToLower();
                if (imgFile.InputStream == null) ShowError("上传文件大小为0。");
                if (!dirName.Compare("media") && !dirName.Compare("files") && !dirName.Compare("file")) if (imgFile.InputStream.Length > maxSize) ShowError("上传文件大小[" + maxSize + "]超过限制。");
                if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1)
                    ShowError("不允许该上传文件的扩展名。\n只允许以下格式：\n" + ((String)extTable[dirName]) + "");
                //创建文件夹
                if (dirName.Compare("image") || dirName.Compare("file")) dirName += "s"; // 将kindEditor默认的文件夹image和file分别加上s。
                dirPath += dirName + "/";
                saveUrl += dirName + "/";
                if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath);
                // var ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo); dirPath += ymd + "/"; saveUrl += ymd + "/";
                if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath);
                var newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
                var filePath = dirPath + newFileName;
                imgFile.SaveAs(filePath);
                var fileUrl = saveUrl + newFileName;
                hash["error"] = 0;
                hash["url"] = fileUrl;
            }
            catch (Exception err)
            {
                hash["error"] = 1;
                hash["message"] = "try{}catch{}错误：" + err.Message;
            }
            context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
            context.Response.Write(JsonConvert.SerializeObject(hash));
            context.Response.End();
        }
        private void ShowError(string message)
        {
            var hash = new Hashtable();
            hash["error"] = 1;
            hash["message"] = message;
            _context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
            _context.Response.Write(JsonConvert.SerializeObject(hash));
            _context.Response.End();
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}